<?php
/**
 * Created by PhpStorm.
 * User: J.H
 * Date: 2017/2/27
 * Time: 23:35
 */

namespace lib\oauth;

use Exception;

class OauthBase
{

    private $errors = array(
        'sys' => array(
            'The state does not match. You may be a victim of CSRF',
            'Missing parameter CODE'
        ),

    );

    function __construct()
    {
        if (!session_id()) {
            session_start();
        }
    }

    /**
     * 设置state并返回其值
     *
     * @param string $prefix
     *
     * @return string
     */
    protected function setState($prefix = '')
    {
        $state = uniqid(rand());
        $_SESSION[$prefix . '_state'] = $state;
        return $state;
    }

    /**
     * 获取服务器保存的state
     *
     * @param string $prefix
     *
     * @return string|null
     */
    protected function getState($prefix = '')
    {
        if (isset($_SESSION[$prefix . '_state'])) {
            return $_SESSION[$prefix . '_state'];
        }
        return null;
    }

    protected function parseUrl($api, $path, $params = array())
    {
        if (!empty($params)) {
            return $api . $path . '?' . http_build_query($params);
        }
        return $api . $path;
    }

    protected function to($url)
    {
        header("Location:{$url}");
        exit;
    }

    protected function error($status, $error_msg = '', $type = 'sys')
    {
        $msg = $error_msg ? $error_msg : $this->errors[$type][$status];
        throw new \Exception($msg);
    }
}